﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using CounterServerModel;


namespace SmartCounters
{
	public partial class UsagePrediction : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
            if (!this.IsPostBack)
            {
                ddAcounts.Items.Clear();

                List<AccountInfo> accounts = new List<AccountInfo>();
                ((MainTemplate)Master).m_PagePermissionFilter = MainTemplate.k_UserPageFilter;
                InformationReader reader = new InformationReader();
                UserInfo userInfo = reader.GetUserInformation(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials, ((MainTemplate)Master).AuthenticatedLoggedInUserCredentials.ID);
                if ((userInfo.UserPermissions & eUserPermissions.ReadOtherAccountInfo) == eUserPermissions.ReadOtherAccountInfo)
                {
                    accounts = reader.GetAllAccounts(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials);
                }
                else if ((userInfo.UserPermissions & eUserPermissions.ReadAssociatedAccountInfo) == eUserPermissions.ReadAssociatedAccountInfo)
                {
                    foreach (int accountID in userInfo.AccountsAssociatedWith)
                    {
                        accounts.Add(reader.GetAccountInformation(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials, accountID));
                    }
                }

                foreach (AccountInfo accountInfo in accounts)
                {
                    string accountLable = accountInfo.Country + " " + accountInfo.City + " " + accountInfo.Street + " " + accountInfo.House + "/" + accountInfo.Apartment;
                    ddAcounts.Items.Add(new ListItem(accountLable, accountInfo.AccountID.ToString()));
                }

                if (ddAcounts.Items.Count > 0)
                {
                    ddAcounts.SelectedIndex = 0;
                }
            }
		}

        protected void btCreatePrediction_Click(object sender, EventArgs e)
        {
            int accountID = int.Parse(ddAcounts.SelectedItem.Value);
            BillingService billingService = new BillingService();
            MonthlyUsage prediction = billingService.GetUsagePredictionForOneMonth(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials, accountID);

            int difference = prediction.Usages.Count / 10 != 0 ? prediction.Usages.Count / 10 : 1;

            for (int i = 0; i < prediction.Usages.Count; i += difference)
            {
                SingleUsage singleUsagePrediction = prediction.Usages.Values[i];
                chart.Series[0].Points.AddXY(singleUsagePrediction.UsageDate, singleUsagePrediction.TotalUsage);
            }
        }
	}
}